package com.soft.collateral.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.soft.collateral.service.FileStrategyService;
import com.soft.collateral.utils.AliyunOSSUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/8/3
 */
//@Service("aliyun")
@Service
public class AliyunFileStrategy implements FileStrategyService {

    private final AliyunOSSUtils aliyunOSSUtils;
    private OSS ossClient;

    public AliyunFileStrategy(AliyunOSSUtils aliyunOSSUtils) {
        this.aliyunOSSUtils = aliyunOSSUtils;
    }

    //初始化
    @PostConstruct
    public void init(){
        //创建OSSClient实例
        ossClient = new OSSClientBuilder()
                .build(aliyunOSSUtils.getEndpoint(), aliyunOSSUtils.getAccessKey(), aliyunOSSUtils.getSecretKey());
    }

    //销毁
    @PreDestroy
    public void destroy(){
        //关闭OSSClient
        ossClient.shutdown();
    }


    //上传文件
    @Override
    public String uploadFile(MultipartFile file) {
        if(file!=null){
            String oldName = file.getOriginalFilename();
            if(StringUtils.hasLength(oldName) && oldName.lastIndexOf(".")>0){
                //处理上传文件名称 fileName  2025/07/28/xxx231ca1.png
                String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
                String filename = date+"/"+ UUID.randomUUID()+oldName;

                try {
                    //获取上传文件的流对象 inputStream
                    InputStream inputStream = file.getInputStream();
                    //调用方法实现上传
                    ossClient.putObject(aliyunOSSUtils.getBucket(), filename, inputStream);

                    //返回上传之后文件路径
                    //格式例如：https://yygh-igeek-user.oss-cn-shanghai.aliyuncs.com/2021/05/06/0a4954938c5e488886924a01eca95ebd1.png
                    String url = "http://"+aliyunOSSUtils.getBucket()+"."+aliyunOSSUtils.getEndpoint()+"/"+filename;
                    return url;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    //删除文件
    @Override
    public boolean deleteFile(String url) {
        String filename = url.replaceAll("http://"+aliyunOSSUtils.getBucket()+"."+aliyunOSSUtils.getEndpoint()+"/" , "");
        try{
            ossClient.deleteObject(aliyunOSSUtils.getBucket(), filename);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }
}